//
//  HQBaseRequestSDK+Custom.m
//  hqedu24olapp
//
//  Created by litianqi on 2018/1/11.
//  Copyright © 2018年 edu24ol. All rights reserved.
//

#import "HQBaseRequestSDK+Custom.h"
#import <AFNetworkReachabilityManager.h>
#import "HQResponseStatus.h"
#import "MJExtension.h"
#import "HQBaseRequestSDKSetting.h"

static NSString * const  kHq_b2cbaseReq_timestamp = @"hq_b2cbaseReq_timestamp";
@implementation HQBaseRequestSDK (Custom)
- (void)hq_startRequestWithUsingCacheWithLife:(NSInteger)lifeSecond Success:(void (^)(id dataResults,BOOL isNetWork))success failure:(void (^)(NSError *error))failure
{
    if (![AFNetworkReachabilityManager sharedManager].isReachable) {
        DDLogInfo(@"HQBaseRequest (Custom)-无网状态");
        [self startB2CRequestUsingCache:YES success:^(YTKBaseRequest *request) {
            [self hq_handleRequestRespone:request success:^(id data) {
                if (success) {
                    success(data,NO);
                }
            } failure:^(NSError *error) {
                if (failure) {
                    failure(error);
                }
            }];
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
        return;
    }
    
    [self updateB2CRequestCacheWithLife:lifeSecond success:^(YTKBaseRequest *request) {
        [self hq_handleRequestRespone:request success:^(id data) {
            if (success) {
                success(data,YES);
            }
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

- (void)hq_startRequestWithResultsHandledBlock:(void (^)(id dataResults,NSError *error))success
{
    [self startB2CRequestWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [self hq_handleRequestRespone:request success:^(id data) {
            if (success) {
                success(data,nil);
            }
        } failure:^(NSError *error) {
            if (success) {
                success(nil,error);
            }
        }];
    } failure:^(NSError *error) {
        if (error && error.code == [self ErrorCode_HaveNoData]) {
            if (success) {
                success(nil,nil);
            }
            return ;
        }
        if (success) {
            success(nil,error);
        }
    }];
}


- (void)hq_startRequestWithUsingCacheSuccess:(void (^)(id dataResults,BOOL isNetWork))success failure:(void (^)(NSError *error))failure
{
    [self hq_startRequestWithUsingCacheWithLife:30 * 24 * 3600 Success:^(id dataResults, BOOL isNetWork) {
        if (success) {
            success(dataResults,YES);
        }

    } failure:^(NSError *error) {
        if (failure) {
            if (!error) {
              NSString *text = self.error.domain;
                text =  (text.length > 0) ? text : @"数据请求失败";
                NSInteger code = self.error ? self.error.code : -1;
                error = [NSError errorWithDomain:text code:code userInfo:nil];
            }
            failure(error);
        }
    }];
    
}

- (void)hq_startRequestWithUsingFirstPageCacheWithJustOne:(BOOL)justOneTime completedBlock:(void (^)(id dataResults,BOOL isNetWork,NSError *error))completedBlock
{
    [self hq_startRequestWithUsingCacheWithJustOne:justOneTime JustFirstPage:[self isFirstPageRequest] completedBlock:completedBlock];
}

- (void)hq_startCommonNoPageRequestWithUsingCacheWithJustOne:(BOOL)justOneTime completedBlock:(void (^)(id dataResults,BOOL isNetWork,NSError *error))completedBlock
{
    [self hq_startRequestWithUsingCacheWithJustOne:justOneTime JustFirstPage:YES completedBlock:completedBlock];
}

- (void)hq_startCommonNoPageRequestWithCacheCompletedBlock:(void (^)(id dataResults,BOOL isNetWork,NSError *error))completedBlock
{
    [self hq_startRequestWithUsingCacheWithJustOne:NO JustFirstPage:YES completedBlock:completedBlock];
}

//针对有网状态，第一页请求有缓存则返回缓存
//- (BOOL)hq_checkFirstPageCache:(NSDictionary *)json durationCacheMax:(NSTimeInterval)durationCacheMax completedBlock:(void (^)(id dataResults,BOOL isNetWork,NSError *error))completedBlock
//{
//    NSTimeInterval lastUpdateTimeStamp = [json[kHq_b2cbaseReq_timestamp] doubleValue];
//    NSTimeInterval duration_cache = [TimeManeger getCurrentValideTimeInterval] - lastUpdateTimeStamp;
//    
//    //TODO: 对缓存校验有效性
//    if (duration_cache/1000 < durationCacheMax) {
//        id data = json[@"data"] ? json[@"data"] : nil;
//        //获取状态
//        HQResponseStatus *status = [HQResponseStatus mj_objectWithKeyValues:json[@"status"]];
//        //TODO: 需要验证缓存有效性：是否过期
//        //状态判断
//        if (status.code == 0) {
//            if (data && [data isKindOfClass:[NSArray class]]) {
//                NSArray *array = data;
//                if (array.count > 0) {
//                    if (completedBlock) {
//                        completedBlock(data,NO,nil);
//                        return YES;
//                    }
//                }
//            } else if (data && [data isKindOfClass:[NSDictionary class]]) {
//                if (completedBlock) {
//                    completedBlock(data,NO,nil);
//                    return YES;
//                }
//            }
//        }
//    }
//    
//    return NO;
//}

- (void)hq_startRequestWithUsingCacheWithJustOne:(BOOL)justOneTime JustFirstPage:(BOOL)justFirstPage completedBlock:(void (^)(id dataResults,BOOL isNetWork,NSError *error))completedBlock
{
    //针对有网状态，第一页请求有缓存则返回缓存
    static NSTimeInterval const durationCacheMax = 90 * 24 * 3600;
    __block BOOL loaded = NO;
     self.currentApiCacheSec = durationCacheMax;
    if (justFirstPage && (durationCacheMax > 0) && [self loadCacheWithError:nil]) {
        NSDictionary *json = self.responseObject;
        if (json && [json isKindOfClass:[NSDictionary class]]) {
            id data = json[@"data"] ? json[@"data"] : nil;
            //获取状态
            HQResponseStatus *status = [HQResponseStatus mj_objectWithKeyValues:json[@"status"]];
            //TODO: 需要验证缓存有效性：是否过期
            //状态判断
            if (status.code == 0) {
                if (data && [data isKindOfClass:[NSArray class]]) {
                    NSArray *array = data;
                    if (array.count > 0 && completedBlock) {
                        loaded = YES;
                        completedBlock(data,NO,nil);
                        
                    }
                } else if (data && [data isKindOfClass:[NSDictionary class]]) {
                    if (completedBlock) {
                        loaded = YES;
                        completedBlock(data,NO,nil);
                    }
                }
            }
        }
    }
    
    [self updateB2CRequestCacheWithLife:durationCacheMax success:^(YTKBaseRequest *request) {
        [self hq_handleRequestRespone:request success:^(id dataResults) {
            if (justOneTime && loaded) {
                return;
            }
            if (completedBlock) {
                completedBlock(dataResults,YES,nil);
            }
        } failure:^(NSError *error) {
            if (justOneTime && loaded) {
                return;
            }
            if (completedBlock) {
                completedBlock(nil,YES,error);
            }
        }];
    } failure:^(NSError *error) {
        if (justOneTime && loaded) {
            return;
        }
        if (completedBlock) {
            completedBlock(nil,YES,error);
        }
    }];
}


- (void)hq_handleRequestRespone:(YTKBaseRequest *)request success:(void (^)(id data))success failure:(void (^)(NSError *error))failure
{
    NSDictionary *json =  request.responseObject;
    //构造自定义response ，写入时间戳：@{@"status":@{@"timestamp":000000000,nil},@"data"}
    if ([request isKindOfClass:NSClassFromString(@"RetryAPI")]) {
        if (!json) {
            json = request.responseJSONObject;
        }
        DDLogInfo(@"<%@>dns retry succ", [request class]);
    }
    
    if (json && [json isKindOfClass:[NSDictionary class]]) {
        DDLogDebug(@"写入时间戳到缓存\n");
        NSDictionary *data = json[@"data"];
        if (!data) {
            return;
        }
    }
    id data = json[@"data"] ? json[@"data"] : nil;
    if ([data isKindOfClass:[NSNull class]]) {
        data = nil;
    }
    //获取状态
    HQResponseStatus *status = [HQResponseStatus mj_objectWithKeyValues:json[@"status"]];
    if (!json[@"status"]) {
        status = nil;
    }
    //状态判断
    __block BOOL isSuccess = NO;
    NSSet *successCodes = [self successCodes];
    [successCodes enumerateObjectsUsingBlock:^(id  _Nonnull obj, BOOL * _Nonnull stop) {
        if (status.code == [obj integerValue]) {
            isSuccess = YES;
            *stop = YES;
        }
    }];
    if (status && isSuccess) {
        if (success) {
            success(data);
        }
    } else if (status.code == [self ErrorCode_HaveNoData]) {
        if (success) {
            if ([data isKindOfClass:[NSNull class]]) {
                success(nil);
                return;
            }
            success(data);
        }
        return;
    }
    else {
        if (failure) {
            NSString *textError = status.msg ?  status.msg : @"数据请求失败啦~";
            failure([NSError errorWithDomain:textError code:status.code userInfo:nil]);
        }
    }
    
}
@end

